package com.qf.rabbitmq1.ps;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerMain2 {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        //服务器所在机器的ip（如果是安装在虚拟机，写虚拟机ip）
        factory.setHost("localhost");
        //amqp协议端口
        factory.setPort(5672);
        //虚拟主机名
        factory.setVirtualHost("cdm");
        //设置虚拟主机对应用户名和密码
        factory.setUsername("cdm");
        factory.setPassword("cdm");

        //获取连接对象（Connection）
        Connection conn = factory.newConnection();
        //获取channel
        Channel channel = conn.createChannel();


        //消费指定队列
        channel.basicConsume("ps.queue2", true, new DefaultConsumer(channel){
            /*
                消息送达
                    String consumerTag: 消费端的唯一标识。一个消费端是唯一不变的
                    Envelope envelope:封装消息路由键、发送端唯一标识、交换机的对象（消息重发时有用）
                    AMQP.BasicProperties properties: 发送端发送过来的一些参数信息
                    byte[] body: 消息体内容
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者标识：" + consumerTag);
                System.out.println("封装对象:" + envelope);
                System.out.println("额外参数:" + properties);
                System.out.println("收到消息：" + new String(body,"utf-8"));

                System.out.println("------------------------");
            }
        });
    }

}
